<?php

namespace app\common\middleware;

use app\common\cache\AdminTokenCache;
use app\common\exception\TokenException;
use app\common\utils\JWTUtils;

class LoginMiddleware
{
    public function handle($request, \Closure $next)
    {
        $token = $request->header('admin-token');
        // 判断接口是否需要登录
        $isNotNeedLogin = $request->controllerObject->isNotNeedLogin();

        // 判断是否需要登录
        if (empty($token) && !$isNotNeedLogin) {
            $request->adminId = 0;
            $request->adminToken = '';
            throw new TokenException('token不存在或已过期');
        }

        $adminId = (new AdminTokenCache())->getAdminToken($token);
        if (empty($adminId) && !$isNotNeedLogin) {
            $request->adminId = 0;
            $request->adminToken = '';
            throw new TokenException('token不存在或已过期');
        } else if (!empty($adminId) && !$isNotNeedLogin) {
            // 校验token是否合法
            try {
                $result = JWTUtils::getPayLoad($token);
                //给request赋值，用于控制器
                $request->adminId = (int)$result->uid ?? 0;
                $request->adminToken = $token;
            } catch (\Exception $e) {
                $request->adminId = 0;
                $request->adminToken = '';
                throw new TokenException('token不存在或已过期');
            }
        }
        return $next($request);
    }
}